package com.bmw.bingfa.controller;

import com.alibaba.fastjson.JSON;
import com.bmw.bingfa.entity.CommonWebUser;
import com.bmw.bingfa.model.TicketUser;
import com.bmw.bingfa.model.http.UserReq;
import com.bmw.bingfa.model.http.UserResp;
import com.bmw.bingfa.service.UserService;
import com.bmw.bingfa.util.ErrorMessage;
import com.bmw.bingfa.util.RedisUtil;
import com.bmw.bingfa.util.bean.BaseRequest;
import com.bmw.bingfa.util.bean.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;

/**
 * Classname: UserController
 * Package: com.bmw.bingfa.controller
 * Description:
 *
 * @Author 余集楠
 * @Create 2024/5/30 0030 16:30
 * @Version 1.8
 */
@RestController
@RequestMapping(value="/user")
@Slf4j
public class UserController {
    private final String USER_PHONE_CODE_BEFORE = "u:p:c:b:";
    @Autowired
    private  UserService userService;
    @Autowired
    private  RedisUtil redisUtil;

    @PostMapping("/getPhoneSmsCode")
    public BaseResponse<Boolean> getPhoneSmsCode(@Valid @RequestBody BaseRequest<UserReq.BaseUserInfo> req) {
        String phone = req.getData().getPhone();
        TicketUser ticketUser = userService.findByPhone(phone);
        //先判断用户存在
        //接下来是调用第三方http接口发送短信验证码，通过验证码存储在redis中，方便后续判断，此处不展示http接口调用了
        if (ticketUser != null) {
            //短信验证码
            String randomCode = "123456";
            redisUtil.set(USER_PHONE_CODE_BEFORE + phone, randomCode,60*30);
            return BaseResponse.ok(true);
        } else return BaseResponse.ok(false);
    }


    @PostMapping("/userPhoneLogin")
    public BaseResponse userPhoneLogin(@Valid @RequestBody BaseRequest<UserReq.LoginUserInfo> req) throws Exception{
        UserReq.LoginUserInfo loginInfo = req.getData();

        Object existObj = redisUtil.get(USER_PHONE_CODE_BEFORE + loginInfo.getPhone());
        if (existObj == null || !existObj.toString().equals(loginInfo.getSmsCode())) {
            return BaseResponse.error(ErrorMessage.SMSCODE_ERROR);
        } else {
            redisUtil.del(USER_PHONE_CODE_BEFORE + loginInfo.getPhone());

            TicketUser ticketUser = userService.findByPhone(loginInfo.getPhone());
            CommonWebUser commonWebUser = new CommonWebUser();
            BeanUtils.copyProperties(commonWebUser, ticketUser);
            String token = UUID.randomUUID().toString().replaceAll("-","");
            //设置token超时时间为1个月，实际根据需求确定
            redisUtil.set(token, JSON.toJSONString(commonWebUser), 60*60*24*30);
            UserResp.BaseUserResp resp = new UserResp.BaseUserResp();
            resp.setToken(token);
            return BaseResponse.ok(resp);
        }

    }

}
